import request from '@/common/request'
import {
	formatDate
} from '@/common/util.js'
import store from '@/store/index.js'
import Config from '@/settings.js'

const $ = {
	getStore(k) {
		// 获取本地存储
		try {
			let v = uni.getStorageSync(k)
			if(v && typeof(v) == 'object' &&  v.expire){
				return (Date.now() - v.time >= v.expire) ? undefined : v.value
			}else{
				return v
			}
		} catch (e) {
			// console.log(e);
		}
	},
	setStore(k, v, time=10000) {
		// 设置本地存储,time为有效期，单位h
		try {
			if(time){
				uni.setStorageSync(k, {
					value: v,
					expire: time*60*60*1000,
					time: Date.now()
				})
			}else{
				uni.setStorageSync(k, v)
			}
		} catch (e) {
			// console.log(e)
		}
	},
	removeStores(arr=[]){
		arr.map(v=>{
			$.removeStore(v)
		})
	},
	removeStore(k) {
		// 删除本地存储
		try {
			uni.removeStorageSync(k)
		} catch (e) {
			// console.log(e)
		}
	},
	clearStore() {
		// 清空本地存储
		try {
			uni.clearStorageSync()
		} catch (e) {
			// console.log(e)
		}
	},
	sleep(delay){
		// delay 延时，单位s
		var start = (new Date()).getTime();
		while ((new Date()).getTime() - start < delay*1000) {
			continue;
		}
	},
	// 检测安卓端是否开启GPS定位
	checkOpenGPSServiceByAndroid(){
		let system = uni.getSystemInfoSync(); // 获取系统信息
		if(system.platform == 'android'){	  // 判断平台
			var context = plus.android.importClass("android.content.Context");
			var locationManager = plus.android.importClass("android.location.LocationManager");
			var main = plus.android.runtimeMainActivity();
			var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
			if(!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)){
				return false
				uni.showModal({
					title: '提示',
					content: '请打开定位服务功能',
					showCancal: false,
					success(){
						if(!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)){
							var Intent = plus.android.importClass('android.content.Intent');
							var Settings = plus.android.importClass('android.provider.Settings');
							var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							main.startActivity(intent); //打开系统设置GPS服务页面
						}else{
							console.info('GPS功能已开启');
						}
					}
				})
			}
			return true
		}
	},
	getLocation() {
		// 获取地理位置
		// if(!$.checkOpenGPSServiceByAndroid())return;
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'wgs84',
				geocode: true,
				success: async (res) => {
					resolve(res)
				},
				fail: (err) => {
					uni.showModal({
						title: '获取位置信息失败',
						content: '请前往手机设置进行设置',
						icon: 'none'
					})
				}
			})
		})
	},
	// 逆地理编码(高德)
	getGeoCode(res){
		uni.request({
			url: 'https://restapi.amap.com/v3/geocode/regeo',
			data: {
				key: 'ac97b5f759ca2abb44f347f86ad894b8',
				location: res,
			},
			success: function(res){
				// console.log('add',res)
			}
		})
	},
	chooseLocation() {
		// 地图上选择位置
		return new Promise((resolve, reject) => {
			// #ifdef MP-TOUTIAO
			this.chooseAddress().then(res=>{
				tt.getLocation({
					success(res1){
						resolve({
							address: res.address,
							lat: res1.latitude,
							lon: res1.longitude
						})
					},
					fail(err){
						$.toast(err, 'fail')
						// reject(err)
					}
				})
			})
			// #endif
			// #ifndef MP-TOUTIAO
				uni.chooseLocation({
					success: (res) => {
						resolve({
							name: res.name,
							address: res.address,
							lat: res.latitude,
							lon: res.longitude
						})
					},
					fail: (err) => {
						reject(err)
					}
				})
			// #endif
		})
	},
	chooseAddress(){
		//选择收货地址
		return new Promise((resolve, reject)=>{
			uni.chooseAddress({
				success: (res)=>{
					resolve({
						name: res.userName,
						phone: res.telNumber,
						address: res.provinceName+res.cityName+res.detailInfo,
						postalcode: res.postalCode
					})
				},
				fail: (err=>{
					reject(err)
				})
			})
		})
	},
	toast(msg, icon = 'none', position = 'center', duration=1500) {
		const params = {
			title: msg,
			position,
			duration: duration,
			mask: true
		}
		if (icon == 'fail') {
			params.image = '/static/image/fail.png'
		} else {
			params.icon = icon
		}
		uni.showToast(params)
	},
	error(msg){
		this.toast(msg, 'fail')
	},
	// 原生toast
	toastx(msg, styles){
		styles = Object.assign({
			icon: '/static/image/alarm.png',
			iconWidth:"20px",
			iconHeight:"20px",
			duration : "long",// 持续3.5s，short---2s
			align : "center",// 水平居中
			verticalAlign : "center",// 垂直底部
		}, styles)
		plus.nativeUI.toast(msg, styles);
	},
	loading(msg) {
		uni.showLoading({
			title: msg
		})
	},
	done() {
		uni.hideLoading()
	},
	confirm(title, content) {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title,
				content,
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	confirmx(title, content) {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title,
				content,
				success: (res) => {
					if(res.confirm){
						resolve(true)
					}else{
						resolve(false)
					}
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	alert(title, content){
		return new Promise((resolve, reject) => {
			uni.showModal({
				title,
				content,
				showCancel: false,
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	showActionSheet(itemList, color) {
		return new Promise((resolve, reject) => {
			uni.showActionSheet({
				itemList,
				itemColor: color,
				success: res => {
					resolve(res.tapIndex)
				},
				fail: (err) => {
					reject(err)
				}
			});
		})
	},
	getProvider(service = 'oauth') {
		return new Promise((resolve, reject) => {
			uni.getProvider({
				service,
				success: (res) => {
					resolve(res.provider)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	checkSession() {
		// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO
		return new Promise((resolve, reject) => {
			uni.checkSession({
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err)
				},
			})
		})
		// #endif
		return new Promise((resolve, reject) => {
			reject()
		})
	},
	chooseImage(options={}) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: options.count || 9,
				sizeType: options.sizeType || 'original',
				sourceType: options.sourceType || ['album'],
				success: (res) => {
					resolve(res)
				},
				fail: err => {
					// console.log(err.errMsg)
				}
			})
		})
	},
	delImage(urls, index){
		$.confirm('提示','确定删除该图片吗?').then(res=>{
			if(res.confirm){
				urls.splice(index, 1)
			}
		})
	},
	getCurrentPage() {
		const pages = getCurrentPages()
		if(!pages.length) return null
		const page = pages[pages.length - 1]
		return page
	},
	/**
	 * 对象转url参数
	 * @param {*} data
	 * @param {*} isPrefix
	 */
	queryParams(data, isPrefix) {
		isPrefix = isPrefix ? isPrefix : false
		let prefix = isPrefix ? '?' : ''
		let _result = []
		for (let key in data) {
			let value = data[key]
			// 去掉为空的参数
			if (['', undefined, null].includes(value)) {
				continue
			}
			if (value.constructor === Array) {
				value.forEach(_value => {
					_result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
				})
			} else {
				_result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
			}
		}

		return _result.length ? prefix + _result.join('&amp;') : ''
	},
	//支付
	pay(data){
		return new Promise((resolve, reject)=>{
			if(data.isOk){
				resolve()
			}else if(data.useMoney){
				$.alert('提示', `扣除余额${data.useMoney}, 还需支付${data.payMoney}`).then(res=>{
					if(res.confirm){
						$.requestPayment(data, resolve, reject)
					}
				})
			}else{
				$.requestPayment(data, resolve, reject)
			}
		})
	},
	uploadImage(res, api){
		let filePath = res.tempFilePaths[0]
		// console.log('upload', filePath)
		return new Promise((resolve, reject)=>{
			uni.uploadFile({
				url: Config.baseUrl+api,
				fileType: 'image',
				filePath: filePath,
				name: 'multipartFile',
				header:{
					Authorization: $.getStore('token')
				},
				success:function(res){
					$.done()
					// console.log(res)
					resolve(JSON.parse(res.data))
				},
				fail:function(err){
					$.done()
					$.toast('上传图片失败', 'fail')
					reject(err)
				}
			})
		})
	},
	genImages(urls){
		if(!urls)return ''
		return urls.split(';').map(v=>{
			return $.genImage(v)
		}).join(';')
	},
	getPlatForm(){
		try {
			const res = uni.getSystemInfoSync();
			return res.platform
		} catch (e) {
				// error
		}
	},
	goto(url, params={}, redirect=false){
		/**
		 * redirect: true 关闭当前页调转
		 * redirect: false 可返回调转
		 */
		let func = redirect ? uni.redirectTo : uni.navigateTo;
		func({
			url: `${url}?params=${encodeURIComponent(JSON.stringify(params))}`
		})
	},
	
	paramsUrl (url, params) {
		let i = 0
		for (let key in params) {
			if (i == 0) {
				url += '?' + key + '=' + params[key]
			} else {
				url += '&' + key + '=' + params[key]
			}
			i++
		}
		return encodeURI(url)
		
	},
	
	// 预览
	previewImage (arrList, current) {
		uni.previewImage({
			urls: arrList,
			current: current,
			longPressActions: {
				itemList: ['保存图片', '分享到微信'],
				success: function(data) {
					uni.downloadFile({
						url: arrList[data.index], 
						success: (res) => {
							if (res.statusCode === 200) {
								let file = res.tempFilePath
								if (data.tapIndex == 0) {
									uni.saveImageToPhotosAlbum({
										filePath: file,
										success: function (errMsg) {
											uni.showToast({
												title: '保存成功',
												icon: 'none',
												position: 'bottom'
											})
										}
									})
								} else {
									uni.share({
										provider: "weixin",
										scene: "WXSceneSession",
										type: 2,
										imageUrl: arrList[data.index],
										success: function (res) {},
										fail: function (err) {
											uni.showToast({
												title: '分享失败',
												icon: 'none'
											})
										}
									})
								}
							}
						}
					})
				},
				fail: function(err) {}
			}
		})
	}
}

export default $
